/**
 * @(#)UpdateController.java, 2010-5-16. 
 * 
 * Copyright 2010 Youdao, Inc. All rights reserved.
 * YOUDAO PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
 */
package com.rsstuan.web.cron.controller;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.ModelAndView;

import com.rsstuan.crawl.impl.CrawlerService;
import com.rsstuan.service.ChannelService;
import com.rsstuan.service.ImageService;
import com.rsstuan.service.ItemService;
import com.rsstuan.storage.data.TuanGouItemData;
import com.rsstuan.storage.impl.JDOImageStorage;
import com.rsstuan.storage.impl.JDOTuanGouChannelStorage;
import com.rsstuan.storage.impl.JDOTuanGouItemStorage;
import com.rsstuan.utils.CityUtils;
import com.rsstuan.utils.ItemUtils;
import com.rsstuan.utils.StringUtils;
import com.rsstuan.web.controller.SpringController;

/**
 *
 * @author guosq
 *
 */
public class UpdateController extends SpringController{
    
    JDOTuanGouItemStorage itemStorage = new JDOTuanGouItemStorage();
    JDOTuanGouChannelStorage channelStorage = new JDOTuanGouChannelStorage();
    ImageService imageService = ImageService.getInstance();
    
    // 这一操作发生在每天00:00,将所有Item设置为无效
    public ModelAndView deactiveItems(HttpServletRequest request,
            HttpServletResponse response)  {
      
        boolean success = itemStorage.deactive(null);
        //ItemService.getInstance().clearCache();
        try {
            if (success) {
                response.getWriter().println("Deactive Success");
            }
            else {
                response.getWriter().println("Deactive Failed");
            }
        }
        catch (Exception e) {
            //do nothing
        }
        return null;
    }
    
    // 这一操作发生在每天00:00,将所有Channel设置为无效
    public ModelAndView deactiveChannels(HttpServletRequest request,
            HttpServletResponse response)  {
      
        boolean success = channelStorage.deactive(null);
        try {
            if (success) {
                response.getWriter().println("Deactive Channels Success");
            }
            else {
                response.getWriter().println("Deactive Channels Failed");
            }
        }
        catch (Exception e) {
            //do nothing
        }
        return null;
    }
    
    // 这一操作将所有当前有活跃商品的频道置为有效
    public ModelAndView  activeChannels(HttpServletRequest request,
            HttpServletResponse response)  {
        List<TuanGouItemData> items = itemStorage.getActivateItems();
        Set<Long> channelIds = new HashSet<Long>();
        for (TuanGouItemData item : items) {
            channelIds.add(item.getChannelId());
        }
        
        channelStorage.activeChannels(channelIds.toArray(new Long[0]));
        return null;
    }
    
    // 这一操作将所有当前有活跃商品的频道置为有效
    public ModelAndView  updateChannelStatus(HttpServletRequest request,
            HttpServletResponse response)  {
        List<TuanGouItemData> items = itemStorage.getActivateItems();
        Set<Long> channelIds = new HashSet<Long>();
        for (TuanGouItemData item : items) {
            channelIds.add(item.getChannelId());
        }
        
        channelStorage.changeChannelStatus(channelIds.toArray(new Long[0]));
        return null;
    }
    
    // 更新频道的总购买数，保持数据一致性
    // 每天更新一次
    public ModelAndView updateChannelOrderNum(HttpServletRequest request,
            HttpServletResponse response) {
        CrawlerService service = new CrawlerService();
        service.doUpdate();
        return null;
    }
    
    public ModelAndView clearCache(HttpServletRequest request,
            HttpServletResponse response) {
    	ChannelService.getInstance().clearCache();
    	ItemService.getInstance().clearCache();
    	return null;
    }
    
    
    public ModelAndView updateImages(HttpServletRequest request,
            HttpServletResponse response) {
    	CrawlerService service = new CrawlerService();
    	String idStr = request.getParameter("id");
    	if (idStr == null) {
	    	List<TuanGouItemData> items = itemStorage.getActivateItems();
	    	for (TuanGouItemData item : items) {
	    		if (!StringUtils.isBlank(item.getImage())
	    				&& imageService.getImage(item.getId()) == null) {
	    			service.crawlImage(item.getId(), item.getImage());
	    		}
	    	}
    	} else {
    		Long id = Long.parseLong(idStr);
    		TuanGouItemData item = itemStorage.getItem(id);
    		if (!StringUtils.isBlank(item.getImage()))  
    			service.crawlImage(item.getId(), item.getImage());
    	}
    	return null;
    }
    
    
    public ModelAndView updateStat(HttpServletRequest request,
            HttpServletResponse response) throws IOException {
    	List<TuanGouItemData> items = itemStorage.getActivateItems();
    	//TuanGouItemData[] itemArray = items.toArray(new TuanGouItemData[0]);
    	//ItemUtils.sortByOrderNumDesc(itemArray);
    	for (TuanGouItemData item : items ) {
    		StringBuilder sb = new StringBuilder();
    		sb.append(item.getId());
    		sb.append("\t");
    		sb.append(item.getChannelId());
    		sb.append("\t");
    		sb.append(item.getOrderNum());
    		sb.append("\n");
    		response.getWriter().write(sb.toString());
    	}
    	return null;
    }
    
    public ModelAndView updateCache(HttpServletRequest request,
            HttpServletResponse response) throws IOException {
    	ItemService itemService = ItemService.getInstance();
    	itemService.updateItems();

    	return null;
    }
}
